package com.example.imagetest;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TestActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "TestActivity";
    private static final int PERMISSION_REQUEST_CODE = 1;
    private ImageView imageView1;
    private ImageView imageView2;
    private Button button;
    private String url1 = "https://www.baidu.com/img/bd_logo1.png";
    private String url2 = "https://img.51miz.com/Element/01/02/75/76/c739ae8e_E1027576_0af26ea9.jpg";

    private String[] strs = new String[]{url1, url2};
    private ImageView[] imageViews;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        Log.e(TAG, "OnCreate...");

        imageView1 = findViewById(R.id.imageView1);
        imageView2 = findViewById(R.id.imageView2);
        imageViews = new ImageView[]{imageView1, imageView2};

        button = findViewById(R.id.button);
        button.setOnClickListener(this);
    }

    @Override
    // 首次安装启动后，用户如果已经被赋予了权限，这里就不会再次请求权限，onRequestPermissionsResult也不会执行
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 检查权限
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.e(TAG, "onRequestPermissionsResult...");
                // downloadImage();
            } else {
                Log.e(TAG, "Permission denied");
            }
        }
    }

    @Override
    public void onClick(View view) {
        // 检查是否有写入外部存储的权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 如果没有权限，请求权限
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        } else {
            // 如果已经有权限，那么直接去下载图片
            for (int i = 0; i < strs.length; i++) {
                Log.e(TAG, String.format("Start downloading image %s", i + 1));
                downloadImage(imageViews[i], strs[i], i + 1);
            }

        }

    }

    private void downloadImage(ImageView imageView, String url, int index) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();

        client.newCall(request).enqueue(new Callback() {

            // 保存文件的绝对路径
            private String absolutePath;

            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                e.printStackTrace();
                Log.e(TAG, "下载图片失败: " + e.getMessage());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    InputStream inputStream = null;
                    OutputStream outputStream = null;

                    try {
                        inputStream = response.body().byteStream();
                        File file = new File(getExternalFilesDir(null), "downloaded_image"+ index + ".jpg");
                        outputStream = new FileOutputStream(file);

                        byte[] buffer = new byte[2048];
                        int bytesRead;
                        // 将输入流写入到输出流
                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            outputStream.write(buffer, 0, bytesRead);
                        }

                        absolutePath = file.getAbsolutePath();
                        Log.e(TAG, String.format("Image %s Position: %s", index, absolutePath));
                        runOnUiThread(() -> displayImage(imageView, absolutePath));
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, "保存图片失败: " + e.getMessage());
                    } finally {
                        if (inputStream != null) inputStream.close();
                        if (outputStream != null) outputStream.close();
                    }
                } else {
                    Log.e(TAG, "请求失败，响应码: " + response.code());
                }
            }
        });

    }

    private void displayImage(ImageView imageView, String imagePath) {
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        imageView.setImageBitmap(bitmap);
    }


}

